package com.zfei.gfb.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.zfei.gfb.device.permit.Button;
import com.zfei.gfb.device.permit.Menu;
import com.zfei.gfb.device.permit.Module;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

public class NewsUtil {


    public static boolean anyNull(Object... objects) {
        for (Object o : objects) {
            if (o == null) {
                return true;
            }
        }
        return false;
    }


    public static Map<String, String> sign(String nonce_str,String timestamp,String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    public static boolean sign(String nickName,int gender,String language, String city, String province, String country, String avatarUrl, String signature, String sessionKey) {
        //注意这里参数名必须全部小写，且必须有序
        String string1 = "{\"nickName\":\"" + nickName + "\",\"gender\": " + gender + ",\"language\":\"" + language + "\",\"city\":\"" + city + "\",\"province\":\"" + province + "\",\"country\":\"" + country + "\",\"avatarUrl\":\"" + avatarUrl + "\"}" + sessionKey;
        System.out.println(string1);
        return signature.equals(SecureUtil.sha1(string1));
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
